angular.module('app').controller('productIntegralCtrl',
    ['$scope', '$rootScope', '$stateParams', '$state', '$http', 'utils', '$timeout', 'activity',
        function ($scope, $rootScope, $stateParams, $state, $http, utils, $timeout, activity) {

            /**
             * 总积分
             */
            $scope.availableBonus = $rootScope.availableBonus;
            /**
             * 购买的数量
             */
            $scope.purchase_quantity = 1;
            /**
             * 订单所需要的积分
             * @type {number}
             */
            $scope.orderTotalPrice = 0;
            /**
             * 是否存在地址
             * @type {boolean}
             */
            $scope.isExistAddress = false;

            $scope.goodsCode = $stateParams.id;
            // $scope.goodsDetails=null; 商品


            $scope.buyCountTime = 0 //用户当日或者当月已经购买的商品数量

            $scope.buyCountTotal = 0 //用户已经购买的总数

            if ($rootScope.isapp) {
                appload = {
                    CallBack: function (type) {

                    }
                };
            }
            $scope.currentPrice=0;

            /**
             * 设置选择的地址
             */
            if (activity.addressInfoDeafult && activity.addressInfoDeafult.addressId) {
                rendAddress(activity.addressInfoDeafult);
                $('#address-info').click(function () {
                    $state.go('address_select');
                });
            } else {
                addressInfo();
            }
            ;

            /**
             * 回退监听
             */
            $scope.$on('$stateChangeStart', function (event) {
                activity.addressInfoDeafult = null;
            });


            /**
             * 设置选择地址
             * @param addressDefault
             */
            function rendAddress(addressDefault) {
                $('#integral-address-default').text(getDefaultAddress(addressDefault));
                $scope.selectAddress = {
                    addressId: addressDefault.addressId,
                    name: addressDefault.consignee,
                    phone: addressDefault.phone,
                    address: getDefaultAddress(addressDefault),
                };
                $scope.isExistAddress = true;
            }

            var exchange = $("#to-exchange");
            var integralReduce = $("#integral-reduce");
            var integralAdd = $("#integral-add");
            /**
             * 判断是否可以购买
             */
            $scope.$watch('remaining', function () {
                if (!$scope.goodsDetails) return
                if (parseInt($scope.goodsDetails.remaining) > 0) {
                    $scope.purchase_quantity = '1';
                    exchange.text('立即兑换');
                    exchange.css("opacity", '1');
                    integralReduce.css("opacity", '1');
                    integralAdd.css('opacity', '1')
                }
                else {
                    exchange.text('已已满标');
                    exchange.css("opacity", '0.6');
                    integralReduce.css("opacity", '0.6');
                    integralAdd.css('opacity', '0.6')
                }
            });

            /**
             * 判断购买数量
             */
            $scope.$watch('purchase_quantity', function () {
                if (!$scope.goodsDetails || !$scope.goodsDetails.remaining) {
                    integralReduce.css("opacity", '0.6');
                    integralAdd.css("opacity", '0.6');
                } else {
                    if ($scope.purchase_quantity <= 1) {
                        integralReduce.css("opacity", '0.6');
                    } else {
                        integralReduce.css("opacity", '1');
                    }
                    $scope.orderTotalPrice = $scope.purchase_quantity *  $scope.currentPrice;
                    if (!$scope.availableBonus || (parseInt($scope.orderTotalPrice) > $scope.availableBonus)) {
                        if ($scope.purchase_quantity > 1) {
                            utils.msg('超出可购范围');
                        }
                        integralAdd.css("opacity", '0.6');
                        exchange.text('积分不足')
                        exchange.css("opacity", '0.6');
                    } else {
                        exchange.text('立即兑换');
                        exchange.css("opacity", '1');
                        integralAdd.css("opacity", '1');
                        if (parseInt($scope.goodsDetails.remaining) > 0) {
                            if ($scope.purchase_quantity <= 0) {
                                exchange.text('立即兑换')
                                exchange.css("opacity", '0.6');
                            } else {
                                exchange.text('立即兑换');
                                exchange.css("opacity", '1');
                            }
                        }
                    }
                }
            });


            $scope.$on('$viewContentLoaded', function (event) {
                setTimeout(function () {
                    if ($rootScope.isapp) {
                        wv.setHeader('商品详情', '0', '-', '0')
                        var Slider = mui('#slider').slider()
                    }
                }, 300)
            });
            /**
             * 获取用户积分
             */
            $scope.getIntegral = function () {
                if ($scope.sole_code) {
                    $http.get(utils.integralSys, {
                        params: {
                            header: utils.header("300312"),
                            body: {
                                userCode: $scope.sole_code,
                            }
                        }
                    }).then(function (res) {
                        if (res.header.re_code == "0000") {
                            $scope.availableBonus = res.body.availableBonus;
                            $scope.getProductDetail();
                        }
                    })
                }
            }


            /**
             * 审核
             */
            $scope.verify = function () {
                var opacity = exchange.css('opacity')
                if (opacity == 1) {
                    if ($scope.purchase_quantity > 0) {
                        if ($scope.isAddress) {
                            if ($scope.isExistAddress) {
                                $scope.showOrder = true;
                            } else {
                                utils.msg('您还未选择收货地址');
                            }
                        } else {
                            $scope.showOrder = true;
                        }
                    }
                }
            };

            /**
             * 取消
             */
            $scope.cancel = function () {
                $scope.showOrder = false;
            };

            /**
             * 提交
             */
            $scope.confirm = function () {
                $scope.showOrder = false;
                if ($scope.goodsDetails) {
                    $http.get(utils.integralSys, {
                            params: {
                                header: utils.header("300170"),
                                body: {
                                    addressId: $scope.isAddress ? $scope.selectAddress.addressId : '',	//地址id	string	唯一标识
                                    discountPrice: $scope.currentPrice,  //	单个商品价格积分	string
                                    exchangeCount: $scope.purchase_quantity + '',  //	兑换数量	string
                                    goodsCode: $scope.goodsDetails.goodsCode + '',  //	商品编码	string
                                    isAddress: $scope.isAddress ? '0' : '1',  //	需要设置收货地址0:需要 1:不需要	string
                                    limitNumber: $scope.goodsDetails.limitNumber,  //	商品限制数量 根据限制类型判断限制数量	string
                                    limitTotal: $scope.goodsDetails.limitTotal ? $scope.goodsDetails.limitTotal : '',  //	商品限制总数	string
                                    limitType: $scope.goodsDetails.limitType,  //	商品限制类型 限制类型0:不限 1:每日限制 2:每月限制	string
                                    userCode: $scope.sole_code,  //
                                }

                            }
                        }
                    ).then(function (res) {
                        if (res.header.re_code == "0000") {
                            utils.msg('兑换成功');
                            $scope.refresh = true;
                            $scope.getIntegral();
                        }
                    });

                }
            };

            /**
             * 商品详情
             */
            $scope.getProductDetail = function () {
                $http.get(utils.integralSys, {
                        params: {
                            header: utils.header("300160"),
                            body: {
                                goodsCode: $stateParams.id,
                                isApp: 0,
                                userCode: $scope.sole_code,
                                limitType: $stateParams.li
                            }
                        }
                    }
                ).then(function (res) {
                    if (res.header.re_code == "0000") {
                        $scope.goodsDetails = res.body.goodsDetails;
                        var fileImgs = $scope.goodsDetails.fileUploadRecords;
                        if (fileImgs && fileImgs.length > 0) {
                            $scope.lastPath = fileImgs[fileImgs.length - 1];
                            $scope.firstPath = fileImgs[0];
                        }
                        $scope.remaining = $scope.goodsDetails.remaining;
                        $("#exchange-count").html($scope.goodsDetails.goodsInfo);
                        $scope.isAddress = !$scope.goodsDetails.isAddress; //收否需要收货地址
                        $scope.buyCountTotal = $scope.goodsDetails.buyCountTotal ? $scope.goodsDetails.buyCountTotal : 0;
                        $scope.buyCountTime = $scope.goodsDetails.buyCountTime ? $scope.goodsDetails.buyCountTime : 0;
                        $scope.currentPrice= $scope.goodsDetails.discountPrice? $scope.goodsDetails.discountPrice: $scope.goodsDetails.originalPrice;
                    }
                });
            }


            /**
             * 减少兑换商品
             */
            $('#div-reduce').click(function () {
                var opacityReduce = integralReduce.css('opacity')
                if (opacityReduce == '1') {
                    if ($scope.purchase_quantity > 1) {
                        $scope.purchase_quantity--;
                        $scope.$apply();//需要手动刷新
                    }
                }
            });
            /**
             * 增加兑换商品
             */
            $('#div-add').click(function () {
                var opacityAdd = integralAdd.css('opacity')
                if (opacityAdd == '1') {
                    if ($scope.goodsDetails.remaining && parseInt($scope.goodsDetails.remaining) > 0
                        && $scope.goodsDetails.remaining > $scope.purchase_quantity) {
                        //console.log(parseInt($scope.purchase_quantity) + parseInt($scope.buyCountTime) + "----11")
                       // console.log(parseInt($scope.purchase_quantity) + parseInt($scope.buyCountTotal) + "---!@@")
                        if ($stateParams.li == 1 || $stateParams.li == 2) {
                            if ($scope.goodsDetails.limitNumber && parseInt($scope.purchase_quantity) + parseInt($scope.buyCountTime) >= parseInt($scope.goodsDetails.limitNumber)) {
                                utils.msg('超出可购范围');
                                integralAdd.css("opacity", '0.6');
                                return
                            }
                        }
                        if ($scope.goodsDetails.limitTotal && parseInt($scope.purchase_quantity) + parseInt($scope.buyCountTotal) >= parseInt($scope.goodsDetails.limitTotal)) {
                            utils.msg('超出可购范围');
                            integralAdd.css("opacity", '0.6');
                            return
                        }
                        $scope.purchase_quantity++;
                        $scope.$apply();//需要手动刷新
                    } else {
                        utils.msg('超出可购范围');
                        integralAdd.css("opacity", '0.6');
                    }

                }
            });


            /**
             * 获取默认地址
             * @param addressDefault
             * @returns {string}
             */
            function getDefaultAddress(addressDefault) {
                if (addressDefault.areaId) {
                    return addressDefault.provinceId + "  " + addressDefault.cityId
                        + "  " + addressDefault.areaId + "  " + addressDefault.address;
                } else {
                    return addressDefault.provinceId + "  " + addressDefault.cityId + "  " + addressDefault.address;
                }
            }


            /**
             * 查询地址列表
             */
            function addressInfo() {
                $scope.sole_code = activity.getSoloCode();
                if ($scope.sole_code) {
                    $http.get(utils.integralSys, {
                        params: {
                            header: utils.header('300440'),
                            body: {
                                phoneNumber: '',
                                //  userCode: this.user_code,
                                userCode: $scope.sole_code,
                                userName: "",

                            }

                        }
                    }).then(function (res) {
                        if (res.header.re_code == "0000") {
                            if (res.body.rows && res.body.rows.length > 0) {//有收货地址
                                for (var i = 0; i < res.body.rows.length; i++) {
                                    var addressDefault = res.body.rows[i];
                                    if (!addressDefault.isDefault) {//0是默认，1非默认
                                        rendAddress(addressDefault);
                                        break;
                                    }
                                }
                                if (!$scope.selectAddress) {
                                    rendAddress(res.body.rows[0])
                                }
                                $('#address-info').click(function () {
                                    $state.go('address_select');
                                })
                            } else {//无收货地址
                                $scope.isExistAddress = false;
                                $('#integral-address-default').text('您还未选择收货地址，马上去填写');
                                $('#address-info').click(function () {
                                    $state.go('address_add')
                                })
                            }
                        }
                    })
                }


            };
            $timeout(function () {
                $scope.sole_code = activity.getSoloCode();
                if (!$scope.availableBonus) {
                    $scope.getIntegral();
                } else {
                    $scope.getProductDetail();
                }
            }, 300)

        }]);